<template>
  <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
    <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0 lg:space-x-4">
      <!-- 搜索输入框 -->
      <div class="flex-1 max-w-md">
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <MagnifyingGlassIcon class="h-5 w-5 text-gray-400" />
          </div>
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="searchPlaceholder"
            class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-primary focus:border-primary"
            @input="handleSearch"
            @keyup.enter="handleSearch"
          >
          <div v-if="searchQuery" class="absolute inset-y-0 right-0 pr-3 flex items-center">
            <button
              @click="clearSearch"
              class="text-gray-400 hover:text-gray-600"
            >
              <XMarkIcon class="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div v-if="filters.length > 0" class="flex flex-wrap items-center space-x-4">
        <div 
          v-for="filter in filters" 
          :key="filter.key"
          class="flex items-center space-x-2"
        >
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">
            {{ filter.label }}:
          </label>
          
          <!-- 下拉选择 -->
          <select
            v-if="filter.type === 'select'"
            v-model="filterValues[filter.key]"
            @change="handleFilter"
            class="block w-full pl-3 pr-10 py-2 text-base border border-gray-300 focus:outline-none focus:ring-primary focus:border-primary rounded-md"
          >
            <option value="">{{ filter.placeholder || '全部' }}</option>
            <option 
              v-for="option in filter.options" 
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </option>
          </select>
          
          <!-- 日期选择 -->
          <input
            v-else-if="filter.type === 'date'"
            v-model="filterValues[filter.key]"
            type="date"
            @change="handleFilter"
            class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
          >
          
          <!-- 日期范围选择 -->
          <div v-else-if="filter.type === 'daterange'" class="flex items-center space-x-2">
            <input
              v-model="filterValues[filter.key + '_start']"
              type="date"
              @change="handleFilter"
              class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
            >
            <span class="text-gray-500">至</span>
            <input
              v-model="filterValues[filter.key + '_end']"
              type="date"
              @change="handleFilter"
              class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
            >
          </div>
          
          <!-- 数字输入 -->
          <input
            v-else-if="filter.type === 'number'"
            v-model="filterValues[filter.key]"
            type="number"
            :placeholder="filter.placeholder"
            @input="handleFilter"
            class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
          >
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex items-center space-x-2">
        <slot name="actions"></slot>
        
        <!-- 重置按钮 -->
        <button
          v-if="hasActiveFilters"
          @click="resetFilters"
          class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          <ArrowPathIcon class="h-4 w-4 mr-1" />
          重置
        </button>
        
        <!-- 搜索按钮 -->
        <button
          @click="handleSearch"
          class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          <MagnifyingGlassIcon class="h-4 w-4 mr-1" />
          搜索
        </button>
      </div>
    </div>

    <!-- 活跃筛选标签 -->
    <div v-if="activeFilterTags.length > 0" class="mt-4 flex flex-wrap items-center space-x-2">
      <span class="text-sm text-gray-500">当前筛选:</span>
      <div class="flex flex-wrap gap-2">
        <span
          v-for="tag in activeFilterTags"
          :key="tag.key"
          class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-light text-primary"
        >
          {{ tag.label }}: {{ tag.value }}
          <button
            @click="removeFilter(tag.key)"
            class="ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full text-primary hover:bg-primary hover:text-white"
          >
            <XMarkIcon class="h-3 w-3" />
          </button>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { 
  MagnifyingGlassIcon, 
  XMarkIcon, 
  ArrowPathIcon 
} from '@heroicons/vue/24/outline'
import { debounce } from '../../utils'

const props = defineProps({
  searchPlaceholder: {
    type: String,
    default: '请输入搜索关键词...'
  },
  filters: {
    type: Array,
    default: () => []
  },
  debounceTime: {
    type: Number,
    default: 300
  }
})

const emit = defineEmits(['search', 'filter', 'reset'])

// 搜索关键词
const searchQuery = ref('')

// 筛选值
const filterValues = ref({})

// 初始化筛选值
props.filters.forEach(filter => {
  if (filter.type === 'daterange') {
    filterValues.value[filter.key + '_start'] = ''
    filterValues.value[filter.key + '_end'] = ''
  } else {
    filterValues.value[filter.key] = filter.defaultValue || ''
  }
})

// 是否有活跃筛选
const hasActiveFilters = computed(() => {
  return searchQuery.value || Object.values(filterValues.value).some(value => value !== '')
})

// 活跃筛选标签
const activeFilterTags = computed(() => {
  const tags = []
  
  // 搜索关键词标签
  if (searchQuery.value) {
    tags.push({
      key: 'search',
      label: '搜索',
      value: searchQuery.value
    })
  }
  
  // 筛选器标签
  props.filters.forEach(filter => {
    if (filter.type === 'daterange') {
      const startValue = filterValues.value[filter.key + '_start']
      const endValue = filterValues.value[filter.key + '_end']
      if (startValue || endValue) {
        tags.push({
          key: filter.key,
          label: filter.label,
          value: `${startValue || '开始'} ~ ${endValue || '结束'}`
        })
      }
    } else {
      const value = filterValues.value[filter.key]
      if (value !== '') {
        let displayValue = value
        
        // 对于选择器，显示选项的标签
        if (filter.type === 'select') {
          const option = filter.options?.find(opt => opt.value === value)
          displayValue = option?.label || value
        }
        
        tags.push({
          key: filter.key,
          label: filter.label,
          value: displayValue
        })
      }
    }
  })
  
  return tags
})

// 防抖搜索
const debouncedSearch = debounce(() => {
  emitSearch()
}, props.debounceTime)

// 处理搜索
const handleSearch = () => {
  debouncedSearch()
}

// 处理筛选
const handleFilter = () => {
  emitSearch()
}

// 发送搜索事件
const emitSearch = () => {
  const searchParams = {
    query: searchQuery.value,
    filters: { ...filterValues.value }
  }
  
  emit('search', searchParams)
  emit('filter', searchParams)
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
  handleSearch()
}

// 移除单个筛选
const removeFilter = (key) => {
  if (key === 'search') {
    searchQuery.value = ''
  } else {
    const filter = props.filters.find(f => f.key === key)
    if (filter?.type === 'daterange') {
      filterValues.value[key + '_start'] = ''
      filterValues.value[key + '_end'] = ''
    } else {
      filterValues.value[key] = ''
    }
  }
  handleSearch()
}

// 重置所有筛选
const resetFilters = () => {
  searchQuery.value = ''
  
  props.filters.forEach(filter => {
    if (filter.type === 'daterange') {
      filterValues.value[filter.key + '_start'] = ''
      filterValues.value[filter.key + '_end'] = ''
    } else {
      filterValues.value[filter.key] = filter.defaultValue || ''
    }
  })
  
  emit('reset')
  handleSearch()
}

// 监听筛选值变化
watch(filterValues, () => {
  // 可以在这里添加额外的逻辑
}, { deep: true })
</script>